package com.htandroid.htandroid.aty;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.ab.soap.AbSoapUtil;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.entity.MrqgdDjList;
import com.htandroid.htandroid.excel.ExcelPurchase_cfqgqd;
import com.htandroid.htandroid.sys.Base_lv_choose;
import com.htandroid.htandroid.sys.Basenvo;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.htandroid.webservice.BuildMremailXMLService;
import com.htandroid.htandroid.webservice.BuildMrqgdXMLService;
import com.htandroid.htandroid.webservice.XMLMrqgdlist;
import com.sendtion.xrichtext.RichTextEditor;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;
import static com.htandroid.htandroid.excel.ExcelGetDir.getExcelDir;

/**
 * Created by lkp on 2015/11/29.
 */
public class mrqgd_orderdetail extends Base_lv_choose {
    private ArrayList<MrqgdDjList> mrqgdlists;
    private ArrayList<MrqgdDjList> newList;
    private ArrayList<MrqgdDjList> isSelectList = new ArrayList<MrqgdDjList>();
    private MrqgdDjList mrqgds;
    private MrqgdDjList mrqgds1;
    public String excelPath;
    public String imgPath;

    @AbIocView(id = R.id.tv_mrqgddel, click = "btnClick")
    TextView tv_mrqgddel;
    @AbIocView(id = R.id.tv_mrqgdorder, click = "btnClick")
    TextView tv_mrqgdorder;
    @AbIocView(id = R.id.chooseall_cb)
    CheckBox chooseall_cb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_mrqgd_orderdetail);
        initview("请购叫货");
        initview2();
        getdata(0);
    }

    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.tv_mrqgddel:
                mrqgd_del(v);
                break;
            case R.id.tv_mrqgdorder:
                mrqgd_order(v);
                break;
        }
    }

    //初始化2
    @Override
    public void initview2() {
        btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newList = new ArrayList<MrqgdDjList>();
                for (int i = 0; i < mrqgdlists.size(); i++) {
                    if (sa.getIsSelected().get(i) == true) {
                        newList.add(mrqgdlists.get(i));
                    }
                }
                excelPath = getExcelDir() + File.separator + "请购叫货" + ".xls";
                ExcelPurchase_cfqgqd cfqgqd = new ExcelPurchase_cfqgqd(mrqgd_orderdetail.this, excelPath, newList, listtype);
                if (newList.size() == 0) {
                    AbToastUtil.showToast(getApplicationContext(), "请选择要分享的数据");
                } else {
                    OnekeyShare oks = new OnekeyShare();
                    oks.setTitle("请购叫货" + ".xls");
                    oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
                        @Override
                        public void onShare(Platform platform,
                                            cn.sharesdk.framework.Platform.ShareParams paramsToShare) {
                            // TODO Auto-generated method stub
                            if (platform.getName().equals("Wechat")) {
                                paramsToShare.setShareType(Platform.SHARE_FILE);
                            }
                        }
                    });
                    imgPath = getExcelDir() + File.separator + "excel.png";
                    writeImg(imgPath);
                    oks.setImagePath(imgPath);
                    oks.setFilePath(excelPath);
                    oks.show(getApplicationContext());
                }
            }
        });

        Intent intent = getIntent();// 创建Intent对象
        //获取传递的对象参数
        mrqgds = (MrqgdDjList) getIntent().getSerializableExtra("mrqgds");
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                linechoose("m", Integer.valueOf("" + id));
            }
        });

        chooseall_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                // 遍历list的长度，将MyAdapter中的map值全部设为true
                for (int i = 0; i < adatperDataList.size(); i++) {
                    sa.getIsSelected().put(i, isChecked);
                    if (isChecked == true) {
                        isSelectList.add(mrqgdlists.get(i));
                    } else {
                        isSelectList.removeAll(isSelectList);
                    }
                }
                sa.notifyDataSetChanged();
            }
        });
    }

    //获取数据
    @Override
    public void getdata(int page) {
        AbDialogUtil.showProgressDialog(mrqgd_orderdetail.this, 0, "正在加载...");
        //参数
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String[] parms = {"user", "cacc_id", "iyear", "ddate", "ddate_dh", "cvencode"};
        String[] vals = {User.nickName, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year(), mrqgds.getdDate(), mrqgds.getdDhDate(), mrqgds.getCvencode()};
        //生成xml
        BuildMrqgdXMLService service = new BuildMrqgdXMLService();
        String xmlstring = service.buildXML("mrqgd_order", InstorageURL.NAME_SPACE, parms, vals, null, null);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "mrqgd_order", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                adatperDataList.clear();
                ArrayList<Map<String, Object>> dataListForInit = new ArrayList<Map<String, Object>>();
                if (result != null) {
                    //解析xml文件,返回列表
                    mrqgdlists = XMLMrqgdlist.paraseCommentInfors(result);
                    for (int i = 0; i < mrqgdlists.size(); i++) {
                        mrqgds1 = mrqgdlists.get(i);
                        //                            aaa.add(item.getPropertyAsString(0));
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("index", (i + 1));
                        map.put("cdepname", mrqgds1.getCdepname());
                        map.put("cinvname", mrqgds1.getcInvname());
                        map.put("cinvstd", mrqgds1.getcInvstd());
                        map.put("cinvunit", mrqgds1.getcInvm_unit());
                        map.put("iquantity", mrqgds1.getiQuantity());
                        map.put("cmemo", mrqgds1.getCmemo());
                        map.put("iprice", mrqgds1.getIprice());
                        dataListForInit.add(map);
                        sa.getIsSelected().put(i, true);
                    }
                } else {
                    AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
                }
                toolDataProvider.initData(dataListForInit);
                loadList();
            }

            @Override
            public void onFailure(String result) {
                AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
                //swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    //删除
    public void mrqgd_del(View v) {
        mrqgdorderact("mrqgd_order_del", "删除定价");
    }

    //叫货
    public void mrqgd_order(View v) {
        isSelectList = new ArrayList<MrqgdDjList>();
        for (int i = 0; i < mrqgdlists.size(); i++) {
            if (sa.getIsSelected().get(i) == true) {
                isSelectList.add(mrqgdlists.get(i));
            }
        }
        if (isSelectList.size() == 0) {
            AbToastUtil.showToast(getApplicationContext(), "请选择需要叫货的存货");
            return;
        }
        mrqgdorderact("mrqgd_order_ok", "叫货");
//        showDialog();
    }

    //删除和保存定价的动作函数
    public void mrqgdorderact(String methodName, final String ctypetext) {
        Boolean ischoose = false;
        String iprice = "";
        // 遍历list的长度，判断是否选中
        HashMap<Integer, Boolean> selectlist = sa.getIsSelected();
        //获取单价修改状态
        HashMap<Integer, String> IpriceUpdated = sa.getIpriceUpdated();
        //先判断存货是否选择,同时还要更改list中的选择标记
        for (int i = 0; i < selectlist.size(); i++) {
            MrqgdDjList mrqgd = (MrqgdDjList) mrqgdlists.get(i);
            if (selectlist.get(i)) {
                ischoose = true;
                mrqgd.setBchecked("1");
                iprice = IpriceUpdated.get(i);
                mrqgd.setIprice(iprice);
                mrqgd.setIamount(Basenvo.customFormat("#####0.00##", Double.valueOf(mrqgd.getiQuantity()) * Double.valueOf(iprice)));
            } else {
                mrqgd.setBchecked("0");
            }
        }
        if (!ischoose) {
            AbToastUtil.showToast(getApplicationContext(), "请选择需要" + ctypetext + "的存货");
            return;
        }
        //刷新列表
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String[] parms = {"user", "cacc_id", "iyear", "ddate", "ddate_dh", "cvencode"};
        String[] vals = {User.uid, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year(), mrqgds.getdDate(), mrqgds.getdDhDate(), mrqgds.getCvencode()};
        //生成xml
        BuildMrqgdXMLService service = new BuildMrqgdXMLService();
        String xmlstring = service.buildXML(methodName, InstorageURL.NAME_SPACE, parms, vals, "in" + parms.length, isSelectList);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, methodName, xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                if (result != null) {
                    //解析xml文件,返回列表
                    mrqgdlists = XMLMrqgdlist.paraseCommentInfors(result);
                    AbToastUtil.showToast(getApplicationContext(), ctypetext + "成功!");
                    if (!"".equals(mrqgds1.getCvenemail())) {
                        showDialog();
                    } else {
                        adatperDataList.clear();
                        ArrayList<Map<String, Object>> dataListForInit = new ArrayList<Map<String, Object>>();
                        if (mrqgdlists.size() > 0) {
                            for (int i = 0; i < mrqgdlists.size(); i++) {
                                MrqgdDjList mrqgds1 = new MrqgdDjList();
                                mrqgds1 = mrqgdlists.get(i);
                                //                            aaa.add(item.getPropertyAsString(0));
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("index", (i + 1));
                                map.put("cdepname", mrqgds1.getCdepname());
                                map.put("cinvname", mrqgds1.getcInvname());
                                map.put("cinvstd", mrqgds1.getcInvstd());
                                map.put("cinvunit", mrqgds1.getcInvm_unit());
                                map.put("iquantity", mrqgds1.getiQuantity());
                                map.put("cmemo", mrqgds1.getCmemo());
                                map.put("iprice", mrqgds1.getIprice());
                                dataListForInit.add(map);
                                sa.getIsSelected().put(i, true);
                            }
                            toolDataProvider.initData(dataListForInit);
                            loadList();
                        } else {
                            //增加一个全部删除或者全部叫货的判断
                            setResult(R.layout.layout_mrqgd_orderdetail / 200000);  //设置返回结果
                            finish();
                        }
                    }
                } else {
                    AbToastUtil.showToast(getApplicationContext(), ctypetext + "失败!数据库错误");
                }
            }

            @Override
            public void onFailure(String result) {
                AbToastUtil.showToast(getApplicationContext(), ctypetext + "失败!数据库错误");
                //swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void showDialog() {
        final View dialogView = LayoutInflater.from(mrqgd_orderdetail.this)
                .inflate(R.layout.basenvo_sendemail, null);
        AlertDialog dialog =
                new AlertDialog.Builder(mrqgd_orderdetail.this)
                        .setTitle("邮件发送确认")
                        .setView(dialogView)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // 获取EditView中的输入内容
                                        RichTextEditor richEditor = (RichTextEditor) dialogView.findViewById(R.id.richEditor);
                                        String content = getEditData(richEditor);
                                        sendEmail(content);
                                    }
                                })
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        adatperDataList.clear();
                                        ArrayList<Map<String, Object>> dataListForInit = new ArrayList<Map<String, Object>>();
                                        if (mrqgdlists.size() > 0) {
                                            for (int i = 0; i < mrqgdlists.size(); i++) {
                                                MrqgdDjList mrqgds1 = new MrqgdDjList();
                                                mrqgds1 = mrqgdlists.get(i);
                                                //                            aaa.add(item.getPropertyAsString(0));
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                map.put("index", (i + 1));
                                                map.put("cdepname", mrqgds1.getCdepname());
                                                map.put("cinvname", mrqgds1.getcInvname());
                                                map.put("cinvstd", mrqgds1.getcInvstd());
                                                map.put("cinvunit", mrqgds1.getcInvm_unit());
                                                map.put("iquantity", mrqgds1.getiQuantity());
                                                map.put("cmemo", mrqgds1.getCmemo());
                                                map.put("iprice", mrqgds1.getIprice());
                                                dataListForInit.add(map);
                                                sa.getIsSelected().put(i, true);
                                            }
                                            toolDataProvider.initData(dataListForInit);
                                            loadList();
                                        } else {
                                            //增加一个全部删除或者全部叫货的判断
                                            setResult(R.layout.layout_mrqgd_orderdetail / 200000);  //设置返回结果
                                            finish();
                                        }
                                        dialog.dismiss();
                                    }
                                }).create();
        dialog.show();
        Button btnPositive = dialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE);
        btnPositive.setTextColor(getResources().getColor(R.color.yellow_press));
    }

    private String getEditData(RichTextEditor richEditor) {
        List<RichTextEditor.EditData> editList = richEditor.buildEditData();
        StringBuffer content = new StringBuffer();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
            }
        }
        return content.toString();
    }

    private void sendEmail(String content) {
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String[] parms = {"cacc_id", "iyear", "mailTo", "mailSubject", "mailBody", "attachmentFileName"};
        String date = mrqgds1.getdDate().replaceFirst("-", "年").replace("-", "月") + "日";
        String dDHate = mrqgds1.getdDhDate().replaceFirst("-", "年").replace("-", "月") + "日";
        String mailSubject = myApplication.getGs_ztname() +
                mrqgds.getCvenname() + " 厨房请购订货（" + date + "）.xls";
        String mailBody = myApplication.getGs_ztname() + " 厨房请购情况，要求到货日期为:" +
                dDHate + "\r\n" + content + "\r\n" + "详见附件";
        String attachmentFileName = myApplication.getGs_ztname() + " 厨房请购订货（" + mrqgds1.getdDate() + "）.xls";
        String[] vals = {myApplication.getGs_ztid(), myApplication.getGs_year(), mrqgds1.getCvenemail(), mailSubject, mailBody, attachmentFileName};
        //String[] vals = {myApplication.getGs_ztid(), myApplication.getGs_year(), "2451399915@qq.com", mailSubject, mailBody, attachmentFileName};
        //生成xml
        BuildMremailXMLService service = new BuildMremailXMLService();
        String xmlstring = service.buildXML(isSelectList, "mrqgdorderemail", InstorageURL.NAME_SPACE, parms, vals, "in" + parms.length);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "mrqgdorderemail", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                adatperDataList.clear();
                ArrayList<Map<String, Object>> dataListForInit = new ArrayList<Map<String, Object>>();
                if (result != null) {
                    String res = result.split("ns1:out>")[1].replace("</", "");
                    if ("001".equals(res)) {
                        AbToastUtil.showToast(getApplicationContext(), "未进行发件人设置，请到合泰软件——系统管理中进行配置!");
                    } else if ("002".equals(res)) {
                        AbToastUtil.showToast(getApplicationContext(), "邮件发送成功!");
                    }
                    if (mrqgdlists.size() > 0) {
                        for (int i = 0; i < mrqgdlists.size(); i++) {
                            MrqgdDjList mrqgds1 = new MrqgdDjList();
                            mrqgds1 = mrqgdlists.get(i);
                            //                            aaa.add(item.getPropertyAsString(0));
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("index", (i + 1));
                            map.put("cdepname", mrqgds1.getCdepname());
                            map.put("cinvname", mrqgds1.getcInvname());
                            map.put("cinvstd", mrqgds1.getcInvstd());
                            map.put("cinvunit", mrqgds1.getcInvm_unit());
                            map.put("iquantity", mrqgds1.getiQuantity());
                            map.put("cmemo", mrqgds1.getCmemo());
                            map.put("iprice", mrqgds1.getIprice());
                            dataListForInit.add(map);
                            sa.getIsSelected().put(i, true);
                        }
                        toolDataProvider.initData(dataListForInit);
                        loadList();
                    } else {
                        //增加一个全部删除或者全部叫货的判断
                        setResult(R.layout.layout_mrqgd_orderdetail / 200000);  //设置返回结果
                        finish();
                    }
                } else {
                    AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
                }
            }

            @Override
            public void onFailure(String result) {
                AbToastUtil.showToast(getApplicationContext(), R.string.sqlerrormsg);
            }
        });
    }
}
